import pandas as pd
import csv
import os
from IPython import embed
from git import Repo
from mailing import send_mail_cse_smtp
from collections import defaultdict
from sys import argv
from subprocess import check_output
import traceback


def get_latest_main_cmt(code_dir):
    repo = Repo(code_dir)

    branch_list = []
    for branch_name in branches:
        try:
            commits = list(repo.iter_commits(branch_name))
            latest_cmt_before_ddl = sorted(
                [
                    cmt
                    for cmt in commits
                    if str(cmt.authored_datetime).split("+")[0] <= ddl
                ],
                key=lambda x: x.authored_datetime,
            )[-1]

            branch_list.append((branch_name, latest_cmt_before_ddl))
        except Exception as e:
            # print(traceback.format_exc())
            pass
            # print("No branch [{}]".format(branch_name))

    if not branch_list:
        raise RuntimeError("No main/master branch found.")

    branch_list = sorted(branch_list, key=lambda x: x[1].authored_datetime)
    latest_branch_name, latest_cmt = branch_list[-1]

    return latest_branch_name, latest_cmt


ddl = "2021-03-19 23:59:59"  # only consider cmt before the ddl
branches = ["main", "master"]  # only consider branches in this range
group_prefix = "D6"  # for TA use


if __name__ == "__main__":
    group_info = pd.read_csv("./final-group.csv")

    gid_projname = dict(zip(group_info["Group ID"], group_info["Project Name"]))

    records = []
    for gid in group_info["Group ID"]:
        if group_prefix and not gid.startswith(group_prefix):
            continue
        code_dir = "./init_codes/group_{}".format(gid)
        branch_name, cmt = get_latest_main_cmt(code_dir)

        print("Checking out {} to {}".format(gid, cmt))

        # check_output(cmd1, shell=True)
        # check_output(cmd2, shell=True)
        # check_output(cmd3, shell=True)
        checkout_cmd = "cd {} && git checkout {} && git checkout {}".format(
            code_dir, branch_name, cmt
        )
        check_output(checkout_cmd, shell=True)
